package com.codemonkey.lq.qd.facotry.config.event;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.codemonkey.lq.qd.builder.BaseBuilder;
import com.codemonkey.lq.qd.builder.BuilderEventListener;
import com.codemonkey.lq.qd.builder.xml.XMLSConfigBuilder;
import com.codemonkey.lq.qd.facotry.config.ExecuteEventMulticaster;
import com.codemonkey.lq.qd.facotry.config.ExecutionEvent;
import com.codemonkey.lq.qd.facotry.config.ExecuteEventListener;
import com.codemonkey.lq.qd.facotry.config.SConfiguration;

/**
 * 仿Spring的
 * 	1. AbstractApplicationEventMulticaster(org.springframework.context.event.AbstractApplicationEventMulticaster)
 *  2. SimpleApplicationEventMulticaster(org.springframework.context.event.SimpleApplicationEventMulticaster)
 * @author LQ
 *
 */
public final class SimpleExecuteEventMulticaster implements ExecuteEventMulticaster,
		BuilderEventListener {

	public final Set<ExecuteEventListener<ExecutionEvent>> applicationListeners;

	private static final SimpleExecuteEventMulticaster instance;
	static {
		instance = new SimpleExecuteEventMulticaster();
	}

	private SimpleExecuteEventMulticaster() {
		applicationListeners = new HashSet<ExecuteEventListener<ExecutionEvent>>(5);
	}

	public static SimpleExecuteEventMulticaster getSingleton() {
		return instance;
	}

	@Override
	public void addListener(ExecuteEventListener<ExecutionEvent> listener) {
		applicationListeners.add(listener);
	}

	@Override
	public void removeListener(ExecuteEventListener<ExecutionEvent> listener) {
		applicationListeners.remove(listener);
	}

	@Override
	public void removeAllListeners() {
		applicationListeners.clear();
	}

	@Override
	public void multicastEvent(final ExecutionEvent event) {
		for (final ExecuteEventListener<ExecutionEvent> listener : applicationListeners) {
			// TODO 事件类型
			//listener.onExecuteFinished(event);
		}
	}

	@Override
	public void builded(BaseBuilder builder, Object currentElement, SConfiguration sc) {
		// 挂接builder完成事件,推入所有通过配置设置的ExecuteEventListener

		if (builder instanceof XMLSConfigBuilder) {			
			Collection<ExecuteEventListener<ExecutionEvent>> executeEventListeners = sc
					.getExecuteEventListeners();
			for (ExecuteEventListener<ExecutionEvent> executeEventListener : executeEventListeners) {
				addListener(executeEventListener);
			}
		}

	}

}
